package kassiopeia.plugin;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>Events are passed from one plugin's output to another plugin's input during
 * task execution.
 *
 * <p>Each event consists of body and headers. Header is a key-value pair.
 *
 * <p>NOTE: Both body and headers values must implement java.io.Serializable.
 */
public final class Event implements Serializable {

    private static final long serialVersionUID = -5867563445312079555L;

    private Serializable body;
    private Map<String, Serializable> headers;

    public Event() {
        this(null);
    }

    public Event(Serializable body) {
        this.headers = new HashMap<String, Serializable>();
        this.body = body;
    }

    public void setHeader(String headerName, Serializable headerValue) {
        headers.put(headerName, headerValue);
    }

    public <T extends Serializable> T getHeader(String headerName, Class<T> clazz) {
        return (clazz.cast(headers.get(headerName)));
    }

    public Serializable getHeader(String headerName) {
        return getHeader(headerName, Serializable.class);
    }

    public void removeHeader(String headerName) {
        headers.remove(headerName);
    }

    public boolean hasHeader(String headerName) {
        return headers.containsKey(headerName);
    }

    public void setBody(Serializable body) {
        this.body = body;
    }

    public <T extends Serializable> T getBody(Class<T> bodyClass) {
        return bodyClass.cast(body);
    }

    public Serializable getBody() {
        return getBody(Serializable.class);
    }

    public boolean hasBody() {
        return (body == null) ? false : true;
    }
}
